<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-card">
        <div class="login-header">
          <h2>登录 KBB</h2>
          <p>欢迎回来！请登录您的账户</p>
        </div>
        
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          class="login-form"
          @submit.prevent="handleSubmit"
        >
          <el-form-item prop="username">
            <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              :prefix-icon="User"
              size="large"
              clearable
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              size="large"
              show-password
              clearable
              @keyup.enter="handleSubmit"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="login-btn"
              :loading="loading"
              @click="handleSubmit"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
        
        <div class="login-footer">
          <span>还没有账号？</span>
          <router-link to="/register" class="register-link">
            立即注册
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { login } from '../api/userApi'
import { getUserInfo } from '../api/serverApi'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref()
const loading = ref(false)

const form = reactive({
  username: '',
  password: ''
})

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
})

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    console.log('开始登录请求...')
    const response = await login({
      username: form.username,
      password: form.password
    })
    
    console.log('登录响应:', response)
    
    if (response.data.success) {
      const token = response.data.data.token
      console.log('获取到token:', token)
      
      // 先保存token
      userStore.setToken(token)
      console.log('token已保存到localStorage:', localStorage.getItem('access-key'))
      
      // 然后获取完整的用户信息
      try {
        console.log('开始调用getUserInfo接口...')
        console.log('当前axios baseURL配置:', 'http://localhost:8980/js')
        console.log('请求URL将是:', 'http://localhost:8980/js/api/auth/userinfo')
        console.log('请求头access-key:', localStorage.getItem('access-key'))
        
        // 添加网络请求监控
        console.log('发起getUserInfo请求前的状态检查:')
        console.log('- localStorage中的token:', localStorage.getItem('access-key'))
        console.log('- userStore中的token:', userStore.token)
        
        const userInfoResponse = await getUserInfo()
        console.log('getUserInfo响应成功:', userInfoResponse)
        console.log('响应数据结构:', JSON.stringify(userInfoResponse, null, 2))
        
        if (userInfoResponse.success) {
          // 保存完整的用户信息（包含role字段）
          userStore.setUserInfo(userInfoResponse.data)
          console.log('用户信息已保存:', userInfoResponse.data)
          ElMessage.success('登录成功！')
          router.push('/')
        } else {
          console.error('getUserInfo返回失败:', userInfoResponse)
          ElMessage.error('获取用户信息失败')
        }
      } catch (userInfoError) {
        console.error('getUserInfo调用异常:', userInfoError)
        console.error('错误详情:', {
          message: userInfoError.message,
          response: userInfoError.response,
          request: userInfoError.request,
          config: userInfoError.config
        })
        ElMessage.error('获取用户信息失败，请重新登录')
        userStore.logout()
      }
    } else {
      console.error('登录失败:', response.data)
      ElMessage.error(response.data.message || '登录失败')
    }
  } catch (error) {
    console.error('登录请求异常:', error)
    ElMessage.error(error.response?.data?.message || '登录失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: rgba(173, 216, 230, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 400px;
   
}

.login-card {
  background: rgba(255, 255, 255, 1);
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.login-header h2 {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.login-header p {
  color: #6b7280;
  font-size: 16px;
  margin: 0;
}

.login-form {
  margin-bottom: 24px;
}

.login-form .el-form-item {
  margin-bottom: 20px;
}

.login-form .el-input {
  border-radius: 12px;
}

.login-form .el-input__wrapper {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
}

.login-form .el-input__wrapper:hover {
  border-color: #4CAF50;
}

.login-form .el-input__wrapper.is-focus {
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1);
}

.login-btn {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  background: #4CAF50;
  border-color: #4CAF50;
  transition: all 0.3s ease;
}

.login-btn:hover {
  background: #45a049;
  border-color: #45a049;
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(76, 175, 80, 0.3);
}

.login-footer {
  text-align: center;
  color: #6b7280;
  font-size: 14px;
}

.register-link {
  color: #4CAF50;
  text-decoration: none;
  font-weight: 500;
  margin-left: 4px;
  transition: color 0.3s ease;
}

.register-link:hover {
  color: #45a049;
  text-decoration: underline;
}

@media (max-width: 480px) {
  .login-card {
    padding: 24px;
  }
  
  .login-header h2 {
    font-size: 24px;
  }
}
</style>